package com.example.demo.controller.aggregate;

import com.example.demo.model.ResponseData;
import com.mongodb.internal.operation.AggregateOperation;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author hanqiang
 * @Classname AggregateController
 * @Date 2020/10/5 22:39
 * @Description:
 */
@RestController
@RequestMapping("/aggregate")
public class AggregateController {
    @Autowired
    MongoTemplate mongoTemplate;

    @ApiOperation(value="聚合函数",notes="group 可多种组合函数查询")
    @GetMapping("/queryAggregate")
    public ResponseData queryAggregate(){
        GroupOperation group= Aggregation.group("price").count().as("priceSum");
        Aggregation aggregation=Aggregation.newAggregation(group);
        AggregationResults<Map> aggregationResults=mongoTemplate.aggregate(aggregation,"shops", Map.class);
        return ResponseData.success(aggregationResults.getMappedResults());
    }

    @ApiOperation(value="聚合函数",notes = "group 和 sort 组合")
    @GetMapping("/queryGroupAndSortAggregate")
    public ResponseData queryGroupAndSortAggregate(){
        GroupOperation group =Aggregation.group("price").count().as("priceSum");
        AggregationOperation sort=Aggregation.sort(Sort.by("price").ascending());
        Aggregation aggregation=Aggregation.newAggregation(group ,sort);
        AggregationResults<Map> aggregationResults=mongoTemplate.aggregate(aggregation,"shops", Map.class);
        return ResponseData.success(aggregationResults.getMappedResults());
    }


}
